package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.LeaseSubList;
import com.isunland.managesystem.entity.LeaseSubListDetailOriginal;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 */

public class LeaseEquipmentDetailFragment extends BaseFragment {
  public static final String EXTRA_ITEM =
      LeaseEquipmentDetailFragment.class.getSimpleName() + ".EXTRA_ITEM";
  public static final String EXTRA_STATUS =
      LeaseEquipmentDetailFragment.class.getSimpleName() + ".EXTRA_STATUS";
  private static final int REQUEST_ALTER = 1;

  private static final int TYPE_DELETE = 6;
  @BindView(R.id.tv_equipmentTypeColon) EditText tvEquipmentTypeColon;
  @BindView(R.id.tv_equipmentArgsRequireColon) EditText tvEquipmentArgsRequireColon;
  @BindView(R.id.tv_leaseAmountColon) EditText tvLeaseAmountColon;
  @BindView(R.id.tv_leaseDaysColon) TextView tvLeaseDaysColon;
  @BindView(R.id.tv_leaseFeeStandardColon) EditText tvLeaseFeeStandardColon;
  @BindView(R.id.tv_leaseFeeTotalColon) EditText tvLeaseFeeTotalColon;
  @BindView(R.id.tv_earnestStarndardColon) EditText tvEarnestStarndardColon;
  @BindView(R.id.tv_earnestFeeTotalColon) EditText tvEarnestFeeTotalColon;
  @BindView(R.id.tv_register) EditText tvRegister;
  @BindView(R.id.tv_registerTime) EditText tvRegisterTime;

  private String mId;
  private LeaseSubList mItem;
  private BaseVolleyActivity mActivity;
  private String status;
  private String mainId;
  //private String mStatus;

  public static LeaseEquipmentDetailFragment newInstance(LeaseSubList item, String status) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_ITEM, item);
    bundle.putString(EXTRA_STATUS, status);
    LeaseEquipmentDetailFragment fragment = new LeaseEquipmentDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  //初始化数据
  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = ((BaseVolleyActivity) getActivity());
    mItem = (LeaseSubList) getArguments().getSerializable(EXTRA_ITEM);
    status = getArguments().getString(EXTRA_STATUS);
    if (mItem != null) {
      mId = mItem.getId();
      mainId = mItem.getMainId();
    }
  }

  //初始化界面
  @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.leaseEquipmentDetail);
      actionBar.setDisplayHomeAsUpEnabled(true);
    }
    View v = inflater.inflate(R.layout.fragment_lease_equipment_detail, container, false);
    ButterKnife.bind(this, v);
    return v;
  }

  //联网请求.
  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    bindData(mItem);
    volleyPostInit(mId);
  }

  protected void volleyPostInit(String id) {
    if (TextUtils.isEmpty(id)) return;
    String mId = mItem.getId();

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_EQUIPMENT_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("获取详情失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        LeaseSubListDetailOriginal original =
            new Gson().fromJson(json, LeaseSubListDetailOriginal.class);
        if (original.getResult() == Base.SUCCESS && original.getData() != null) {

          bindData(original.getData());
        } else {
          ToastUtil.show("获取详情失败!");
        }
      }
    });
  }

  private void bindData(LeaseSubList data) {
    if (data == null) return;
    tvEquipmentTypeColon.setText(data.getDeviceType());
    tvEquipmentArgsRequireColon.setText(data.getDeviceParamRequire());
    tvLeaseAmountColon.setText(data.getLeaseNum());
    tvLeaseDaysColon.setText(data.getLeaseDays());
    tvLeaseFeeStandardColon.setText(data.getLeaseCostLevel());
    tvLeaseFeeTotalColon.setText(data.getLeaseCostTotal());
    tvEarnestStarndardColon.setText(data.getDepositStandard());
    tvEarnestFeeTotalColon.setText(data.getDepositCostTotal());
    tvRegister.setText(data.getRegStaffName());
    tvRegisterTime.setText(data.getRegDate());
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (status == null) {
      return;
    }
    if (status.equals(DataStatus.NEW) || status.equals(DataStatus.NEWBACK) || status.equals(
        DataStatus.ORDER_CANCEL) || status.equals(DataStatus.BACK_ORDER_PUBLISH)) {
      inflater.inflate(R.menu.menu_alter_delete, menu);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      //case android.R.id.home:
      //    mActivity.finish();
      //    break;
      case R.id.menu_item_alter:
        LeaseEquipmentUpdateActivity.startActivityForResult(this, mActivity, mItem, mainId,
            REQUEST_ALTER);
        break;
      //case R.id.menu_item_submit:
      //    volleypostUpdateStatus(mId, TYPE_SUBMIT);
      //    break;
      case R.id.menu_item_delete:
        volleypostDelete(mId);
        break;
      //case R.id.menu_item_cancel:
      //    volleypostUpdateStatus(mId, TYPE_CANCEL);
      //    break;
      //case R.id.menu_item_reminder:
      //    volleypostUpdateStatus(mId,TYPE_REMINDER);
      //    break;
      default:
        break;
    }

    return super.onOptionsItemSelected(item);
  }

  private void volleypostDelete(String id) {
    if (TextUtils.isEmpty(id)) return;

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_EQUIPMENT_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", id);

    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("操作失败");
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base original = new Gson().fromJson(arg0, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show(R.string.deleteSuccess);
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        } else {
          ToastUtil.show(R.string.deleteFail);
        }
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    switch (requestCode) {
      case REQUEST_ALTER:
        //volleyPostInit();
        mActivity.setResult(Activity.RESULT_OK);
        mActivity.finish();
        break;
      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
